package demo.aspect.common;

import demo.annotation.Secured;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Aspect
public class SecuredMethodAspect {

    @Pointcut("@annotation(demo.annotation.Secured)")
    public void callSecured() {
    }

    @Around("callSecured()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Secured secured = getAnnotation(joinPoint, Secured.class);
        Signature signature = joinPoint.getSignature();
        if (secured.isLocked()) {
            System.out.println(signature + "is locked");
        } else {
            System.out.println(signature + "is not locked");
        }
        return secured.isLocked() ? null : joinPoint.proceed();
    }

    private static <T extends Annotation> T getAnnotation(ProceedingJoinPoint joinPoint, Class<T> clazz) {
        MethodSignature sign = (MethodSignature) joinPoint.getSignature();
        Method method = sign.getMethod();
        return method.getAnnotation(clazz);
    }
}
